import { createStore } from "vuex";

export default createStore({
  state: {
    cartList: [],
  },
  getters: {
    // 计算总数量
    allNum(state) {
      let num = 0;
      state.cartList.forEach((item) => {
        num += item.num;
      });
      return num;
    },
    // 计算总价格
    allPrice(state) {
      let price = 0;
      state.cartList.forEach((item) => {
        price += item.num * item.price;
      });
      return price;
    },
  },
  mutations: {
    // 加入购物车
    add(state, val) {
      console.log(val);
      let flag = false;
      state.cartList.forEach((item) => {
        if (item.name == val.name) {
          item.num = val.num;
          flag = true;
        }
      });
      if (flag == false) {
        val.num = 1;
        state.cartList.push(val);
      }
      console.log(state.cartList);
    },
    // 清空购物车
    remove(state) {
      state.cartList.forEach((item) => {
        item.num = 0;
      });
      state.cartList = [];
    },
  },
  actions: {},
  modules: {},
});
